use crate::traits::{SmartModuleFactory, SmartModule, SmartModuleMetadata, SmartModuleType, SmartModuleConfig};
use crate::transforms::{FieldMapper, JsonTransformer};
use crate::filters::{ConditionFilter};
use fluviox_shared::Result;
use serde_json::{json, Value};
use std::collections::HashMap;

/// SmartModule注册表
pub struct SmartModuleRegistry {
    factories: HashMap<String, Box<dyn Fn() -> Box<dyn SmartModule> + Send + Sync>>,
}

impl SmartModuleRegistry {
    pub fn new() -> Self {
        let mut registry = Self {
            factories: HashMap::new(),
        };
        
        // 注册内置模块
        registry.register_builtin_modules();
        registry
    }
    
    /// 注册内置模块
    fn register_builtin_modules(&mut self) {
        // 注册转换器
        self.factories.insert(
            "field-mapper".to_string(),
            Box::new(|| Box::new(FieldMapper::new()))
        );
        
        self.factories.insert(
            "json-transformer".to_string(),
            Box::new(|| Box::new(JsonTransformer::new()))
        );
        
        // 注册过滤器
        self.factories.insert(
            "condition-filter".to_string(),
            Box::new(|| Box::new(ConditionFilter::new()))
        );
    }
    
    /// 注册自定义模块
    pub fn register<F>(&mut self, name: String, factory: F)
    where
        F: Fn() -> Box<dyn SmartModule> + Send + Sync + 'static,
    {
        self.factories.insert(name, Box::new(factory));
    }
    
    /// 创建模块实例
    pub fn create_module(&self, name: &str) -> Result<Box<dyn SmartModule>> {
        if let Some(factory) = self.factories.get(name) {
            Ok(factory())
        } else {
            Err(fluviox_shared::FluvioXError::Internal(
                format!("未知的SmartModule类型: {}", name)
            ))
        }
    }
    
    /// 获取支持的模块列表
    pub fn list_modules(&self) -> Vec<String> {
        self.factories.keys().cloned().collect()
    }
}

impl SmartModuleFactory for SmartModuleRegistry {
    fn create(&self, config: SmartModuleConfig) -> Result<Box<dyn SmartModule>> {
        self.create_module(&config.name)
    }
    
    fn supported_modules(&self) -> Vec<SmartModuleMetadata> {
        vec![
            SmartModuleMetadata {
                name: "field-mapper".to_string(),
                version: "1.0.0".to_string(),
                description: "字段映射转换器".to_string(),
                module_type: SmartModuleType::Transform,
                config_schema: json!({
                    "type": "object",
                    "properties": {
                        "field_mappings": {
                            "type": "object",
                            "description": "字段重命名映射"
                        },
                        "fields_to_remove": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "要删除的字段列表"
                        },
                        "fields_to_add": {
                            "type": "object",
                            "description": "要添加的字段"
                        },
                        "default_values": {
                            "type": "object",
                            "description": "默认值映射"
                        },
                        "keep_unmapped": {
                            "type": "boolean",
                            "default": true,
                            "description": "是否保留未映射的字段"
                        }
                    }
                }),
                example_config: json!({
                    "field_mappings": {
                        "old_name": "new_name",
                        "user_id": "id"
                    },
                    "fields_to_remove": ["temp_field"],
                    "fields_to_add": {
                        "processed_at": "2024-01-01T00:00:00Z"
                    },
                    "keep_unmapped": true
                }),
            },
            SmartModuleMetadata {
                name: "json-transformer".to_string(),
                version: "1.0.0".to_string(),
                description: "JSON转换器".to_string(),
                module_type: SmartModuleType::Transform,
                config_schema: json!({
                    "type": "object",
                    "properties": {
                        "extractions": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "source_path": {"type": "string"},
                                    "target_field": {"type": "string"},
                                    "required": {"type": "boolean", "default": false},
                                    "default_value": {}
                                },
                                "required": ["source_path", "target_field"]
                            },
                            "description": "JSONPath提取规则"
                        },
                        "flatten": {
                            "type": "boolean",
                            "default": false,
                            "description": "是否展平嵌套对象"
                        },
                        "flatten_separator": {
                            "type": "string",
                            "default": ".",
                            "description": "展平分隔符"
                        },
                        "remove_null": {
                            "type": "boolean",
                            "default": false,
                            "description": "是否移除空值"
                        },
                        "output_mode": {
                            "type": "string",
                            "enum": ["merge", "extract_only", "replace"],
                            "default": "merge",
                            "description": "输出模式"
                        }
                    }
                }),
                example_config: json!({
                    "extractions": [
                        {
                            "source_path": "$.user.name",
                            "target_field": "username",
                            "required": true
                        },
                        {
                            "source_path": "$.metadata.timestamp",
                            "target_field": "event_time",
                            "required": false,
                            "default_value": null
                        }
                    ],
                    "flatten": true,
                    "flatten_separator": "_",
                    "remove_null": true,
                    "output_mode": "merge"
                }),
            },
            SmartModuleMetadata {
                name: "condition-filter".to_string(),
                version: "1.0.0".to_string(),
                description: "条件过滤器".to_string(),
                module_type: SmartModuleType::Filter,
                config_schema: json!({
                    "type": "object",
                    "properties": {
                        "conditions": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "field_path": {"type": "string"},
                                    "operator": {
                                        "type": "string",
                                        "enum": ["eq", "ne", "gt", "gte", "lt", "lte", "contains", "not_contains", "starts_with", "ends_with", "in", "not_in", "exists", "not_exists"]
                                    },
                                    "value": {},
                                    "ignore_case": {"type": "boolean", "default": false}
                                },
                                "required": ["field_path", "operator", "value"]
                            },
                            "description": "过滤条件列表"
                        },
                        "logic": {
                            "type": "string",
                            "enum": ["and", "or"],
                            "default": "and",
                            "description": "条件组合逻辑"
                        }
                    },
                    "required": ["conditions"]
                }),
                example_config: json!({
                    "conditions": [
                        {
                            "field_path": "status",
                            "operator": "eq",
                            "value": "active"
                        },
                        {
                            "field_path": "user.age",
                            "operator": "gte",
                            "value": 18
                        }
                    ],
                    "logic": "and"
                }),
            },
        ]
    }
    
    fn validate_config(&self, module_type: &str, config: &Value) -> Result<()> {
        // 基础配置验证
        match module_type {
            "field-mapper" => {
                // 验证字段映射配置
                if let Some(mappings) = config.get("field_mappings") {
                    if !mappings.is_object() {
                        return Err(fluviox_shared::FluvioXError::Validation(
                            "field_mappings必须是对象".to_string()
                        ));
                    }
                }
                Ok(())
            },
            "json-transformer" => {
                // 验证JSON转换器配置
                if let Some(extractions) = config.get("extractions") {
                    if !extractions.is_array() {
                        return Err(fluviox_shared::FluvioXError::Validation(
                            "extractions必须是数组".to_string()
                        ));
                    }
                }
                Ok(())
            },
            "condition-filter" => {
                // 验证条件过滤器配置
                if let Some(conditions) = config.get("conditions") {
                    if !conditions.is_array() {
                        return Err(fluviox_shared::FluvioXError::Validation(
                            "conditions必须是数组".to_string()
                        ));
                    }
                } else {
                    return Err(fluviox_shared::FluvioXError::Validation(
                        "缺少必需字段: conditions".to_string()
                    ));
                }
                Ok(())
            },
            _ => Err(fluviox_shared::FluvioXError::Internal(
                format!("未知的模块类型: {}", module_type)
            )),
        }
    }
}

impl Default for SmartModuleRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// 全局SmartModule注册表实例
static mut GLOBAL_REGISTRY: Option<SmartModuleRegistry> = None;
static INIT: std::sync::Once = std::sync::Once::new();

/// 获取全局SmartModule注册表
pub fn get_global_registry() -> &'static SmartModuleRegistry {
    unsafe {
        INIT.call_once(|| {
            GLOBAL_REGISTRY = Some(SmartModuleRegistry::new());
        });
        GLOBAL_REGISTRY.as_ref().unwrap()
    }
}

/// 获取可变的全局SmartModule注册表
pub fn get_global_registry_mut() -> &'static mut SmartModuleRegistry {
    unsafe {
        INIT.call_once(|| {
            GLOBAL_REGISTRY = Some(SmartModuleRegistry::new());
        });
        GLOBAL_REGISTRY.as_mut().unwrap()
    }
}
